import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import home from '@/components/home'
import login from '@/components/login'
import store from '@/store'
import CONFIG from '@/config'

Vue.use(Router)

const router = new Router({
  // base: '/app/',
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      meta: {'title': '首页'}
    },
    {
      path: '/home',
      name: 'home',
      component: home,
      meta: {'title': '我的家园'}
    },
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: {'title': '欢迎您'}
    }
  ]
})
router.beforeEach((to, from, next) => {
  // store.commit('app_setSlideName')
  if (store.state && !to.matched.some(v => v.meta.disableLoading)) { // 路由跳转，显示菊花~ Author by Dio Zhu. on 2017.2.17
    store.commit('app_openLoading')
  }
  function setSlide(slide) {
    store.commit('app_setSlideName', slide)
  }
  if (to.query.key) {
    if (parseInt(from.query.key) > parseInt(to.query.key)) {
      console.log('后退')
      setSlide('left')
    } else {
      setSlide('right')
      console.log('前进')
    }
  } else {
    if (from.name) {
      setSlide('left')
      console.log('后退')
    } else {
      setSlide('right')
      console.log('前进')
    }
  }
  next()
})
router.afterEach(route => {
  if (route.meta && route.meta.title) {
    document.title = route.meta.title
  } else {
    document.title = CONFIG.TITLE
  }
  try { // 隐藏loading
    if (store && store.state) {
      setTimeout(function () {
        store.commit('app_closeLoading')
      }, 400)
    }
  } catch (e) {
    console.error('router.afterEach: ', e)
  }
})
let p = router.push
let r = router.replace
router.push = function (params) {
  if (params.query) {
    params.query.key = Date.now()
  } else {
    params.query = {key: Date.now()}
  }
  p.call(router, params)
}
router.replace = function (params) {
  if (params.query) {
    params.query.key = Date.now()
  } else {
    params.query = {key: Date.now()}
  }
  r.call(router, params)
}
// 导出router对象
export default router
